package ui.svr;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BoxLayout;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.awt.event.ActionEvent;

public class MainFrame {

	private JFrame frame;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MainFrame window = new MainFrame();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public MainFrame() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	public final int sPort=3030;
	//private Thread tr;
	private SvrInThread sit=new SvrInThread(sPort);
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 300, 200);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		JPanel headPanel = new JPanel();
		headPanel.setLayout(new BoxLayout(headPanel,BoxLayout.Y_AXIS));
		frame.getContentPane().add(headPanel, BorderLayout.CENTER);
		headPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
		JPanel endPanel = new JPanel();
		endPanel.setLayout(new FlowLayout());
		frame.getContentPane().add(endPanel,BorderLayout.PAGE_END);
		JLabel labHead =new JLabel("Port");
		labHead.setAlignmentX(Component.CENTER_ALIGNMENT);
		try{
			labHead.setText(InetAddress.getLocalHost()+" Port:3030"); 
			}catch(Exception e)
			{
				labHead.setText("error");
			}
		
		headPanel.add(labHead);
		headPanel.add(Global.labGlobal);
		endPanel.add(Global.btnGlobal);
		Global.labGlobal.setAlignmentX(Component.CENTER_ALIGNMENT);
		Global.btnGlobal.setAlignmentX(Component.CENTER_ALIGNMENT);
		Global.btnGlobal.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e)
			{
				
				if(Global.flag)
				{
					//service stop
					Global.flag=false;
					if(sit.shutinput())
					{
						System.out.println("din is closed");
					}
					else
					{
						System.out.println("din is alive");
					}
					//SimpleClient sc =new SimpleClient("127.0.0.1",sPort);
					/*try{						
						sc.SetUp();					
					}catch(Exception e1)
					{
						System.out.println("closing failed");
						Global.flag=true;
					}*/
					sit.SClose();
					Global.btnGlobal.setText("RUN");
					Global.labGlobal.setText("SLEEPING");
					//sc.SClose();
					}
				else
				{
					//service start
					Global.flag=true;
					Global.pool.execute(sit);	
					Global.btnGlobal.setText("STOP");
					Global.labGlobal.setText("RUNNING");
				}
			}
		});
		
	}

}
